﻿require "mime"
---@class Client
local Client = class("Backend")

-- params   protocalName        协议名
--  params  objects             协议参数 tabls
-- params   otherProtocalData   例如download，upload等协议的参数
function Client:send(protocalName, objects, otherProtocalData)
    local xhr = cc.XMLHttpRequest:new()
    
    -- 其他参数
    local params = ""
    objects = objects or {}

    local userName = gContext:getUser() or "zhukai"
    objects['userName'] = userName
    for key, var in pairs(objects) do
        params = params.."&" .. key .. "="..var
    end
    
    -- 如果用户名为空，则说明没有登录信息，故意使请求报错
    local auth = mime.b64(userName..":"..gContext:getPassword())
    xhr:setRequestHeader("Authorization", getAuthHeader())
   
    local host = "http://59.110.154.168:8084/BI/api/map.new.action"
    local host = host .. "?d=" .. protocalName
    local uri =  "method="..protocalName..params   

    print('REQUESTING:', uri)

    -- 下载请求    
    if (protocalName == "export") then
        xhr:open("DOWNLOAD", host.."?"..uri,false, otherProtocalData)
    -- 上传请求    
    elseif (protocalName == "checkImport") then 
        xhr:open("UPLOAD", host.."?"..uri,false, otherProtocalData)
    -- 普通请求
    else
        xhr:open("POST", host)
    end

    local function onReadyStateChange()
        if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
            GlobalEventDispatcher:getInstance():dispatchEvent(Event.new("global.event.service."..protocalName, xhr.response))
        else
            print("Http ERROR Status Code:", protocalName, xhr.status, xhr.responseCode)
            GlobalEventDispatcher:getInstance():dispatchEvent(Event.new("global.event.service.error", xhr))
        end
        gContext.root.loadingLayer:setVisible(false)
        -- gContext.root.__editEnable = true
    end
    xhr:registerScriptHandler(onReadyStateChange)
    xhr:send(uri)   
    gContext.root.loadingLayer:setVisible(true)
    -- gContext.root.__editEnable = false
end

-- configManager接口
-- http://10.130.120.54:8082/api/viewFile.do?appName=animal_dev0&fileName=world_map_config.xml
function Client:send2configManager(action, fileName, objects)
    --[[
    local xhr = cc.XMLHttpRequest:new()
    
    local params = ""
    if (objects) then 
        for key, var in pairs(objects) do
            params = params.."&" .. key .. "="..var
        end
    end 
    
    local auth = mime.b64(gContext:getUser()..":"..gContext:getPassword())
    if (gContext:getUser() ~= "") then 
        xhr:setRequestHeader("Authorization", getAuthHeader())
    end 
   
    local host = "http://192.168.1.27:8081/api/"..action..".do" 
    local uri =  "appName=animal_dev0"..params   

    xhr:open("POST", host)

    local function onReadyStateChange()
        if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
            print("Http Status Code:"..xhr.statusText.." "..action)

            local evt = Event.new("global.event.service."..action, xhr.response)
            evt.fileName = fileName
            GlobalEventDispatcher:getInstance():dispatchEvent(evt)
        else
            print("Http ERROR uri:", uri)
            print("Http ERROR xhr.readyState is:", xhr.readyState, "xhr.status is: ",xhr.status,xhr.statusText)
            print("Http ERROR Status Code:" .. xhr.status)
            GlobalEventDispatcher:getInstance():dispatchEvent(Event.new("global.event.service.error",xhr))
        end
         gContext.root.loadingLayer:setVisible(false)
    end
    xhr:registerScriptHandler(onReadyStateChange)
    xhr:send(uri)   
    gContext.root.loadingLayer:setVisible(true)
    --]]
end

-- ------------------  configManager服务 ----------------
function Client:getTileEditorConflictConfig()
    local objects = {}
    objects["fileName"] = "editor_conflict_config.xml"
    self:send2configManager("viewFile","editor_conflict_config", objects)
end

function Client:getWorldMap()
    local objects = {}
    objects["fileName"] = "world_map_config.xml"
    self:send2configManager("viewFile","world_map_config", objects)
end

-- 合并 fileName,content
function Client:merge(objects)
    -- local objects = {}
    -- objects["fileName"] = "customize_config.xml"
    -- objects["content"] = "1"
    self:send2configManager("modifyFile","customize_config", objects)
end

-- 发布
function Client:deploy()
    local objects = {}
    objects["fileName"] = "customize_config.xml"
    self:send2configManager("deploy", "customize_config", objects)
end

-- ------------------------------------------------------
-- ------------------------------------------------------
-- ------------------  游戏服务 -------------------------
-- ------------------------------------------------------
-- ------------------------------------------------------

-- 下载指定类别的关卡顺序
-- path 下载路径
function Client:export(objects, path)
    self:send("export",objects, path)
end

function Client:checkImport(objects, path)
   self:send("checkImport",objects, path)
end

function Client:doImport(objects)
   self:send("import",objects)
end

-- 获得所有关卡id和描述，用于获取关卡列表
function Client:getSimplfy()
    self:send("getSimplfy")
end

-- 获得全部关卡数据，字符串形式
function Client:get()
    self:send("get")
end

-- 获得全部关卡数据，xml形式
function Client:all()
    self:send("all")
end

function Client:config()
    self:send("config")
end

-- 获得指定关卡数据
function Client:detail(objects)
    self:send("detail", objects)
end

-- 新增关卡
function Client:add(objects)
    self:send("add",objects)
end

-- 批量新增关卡
function Client:batchAdd(objects)
    self:send("batchAdd",objects)
end

-- 删除过关记录
function Client:delPassLevelRecord(objects)
    self:send("delPassLevelRecord",objects)
end

-- 删除关卡
function Client:del(objects)
    self:send("del",objects)
end

function Client:adminDel(objects)
    -- self:send("adminDel",objects)
end

-- 保存关卡
function Client:update(objects)
    LocalService.OnService("update", objects)
    self:send("update",objects)
end

-- 超级管理员保存关卡，可以跳过lock
function Client:adminUpdate(objects)
    self:send("adminUpdate",objects)
end

-- 锁定关卡
function Client:lock(objects)
    self:send("lock",objects)
end

-- 解锁关卡
function Client:unlock(objects)
    self:send("unlock",objects)
end

-- 超级用户解锁关卡
function Client:adminUnlock(objects)
    self:send("adminUnlock", objects)
end

-- 获得dev的关卡配置
function Client:getCustomizeConfig()
    self:send("getCustomizeConfig")
end

function Client:duplicate(param)
    self:send("duplicate",param)
end

function Client:globalLock()
    self:send("globalLock")
end

function Client:globalUnlock()
    self:send("globalUnlock")
end

function Client:updateLevelId(param)
    self:send("updateLevelId",param)
    self.updateLevelIdParam = param
end

return Client